import { computed, defineComponent, watchEffect } from "vue";
import { useRender } from "@/framework/vue/hooks";
import { ConfigProvider, theme } from "ant-design-vue";
import zhCN from "ant-design-vue/es/locale/zh_CN";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";

dayjs.locale("zh-cn");

export default defineComponent({
  name: "ThemeProvider",
  props: {
    theme: { type: String, default: "dark" },
  },
  setup(props, { slots }) {
    const { token } = theme.useToken();

    watchEffect(
      () => {
        const variables = {
          "--text-color": token.value.colorText,
          "--disabled-color": token.value.colorTextDisabled,
          "--text-color-secondary": token.value.colorTextSecondary,
          "--text-color-tertiary": token.value.colorTextTertiary,

          "--primary-color": token.value.colorPrimary,
          "--primary-color-1": token.value["blue-1"],
          "--info-color": token.value.colorInfo,
          "--success-color": token.value.colorSuccess,
          "--warning-color": token.value.colorWarning,
          "--error-color": token.value.colorError,

          "--color-bg-base": token.value.colorBgBase,
          "--color-bg-container": token.value.colorBgContainer,
          "--color-bg-text-hover": token.value.colorBgTextHover,

          "--border-radius": `${token.value.borderRadius}px`,
          "--border-color": token.value.colorBorder,
          "--box-shadow": token.value.boxShadow,
        };

        Object.entries(variables).forEach(([key, value]) => {
          document.documentElement.style.setProperty(key, value?.toString());
        });
      },
      { flush: "post" },
    );

    const algorithm = computed(() => {
      const algorithm = [theme.defaultAlgorithm];
      if (props.theme === "dark") {
        algorithm.push(theme.darkAlgorithm);
      }
      return algorithm;
    });

    useRender(() => (
      <ConfigProvider locale={zhCN} theme={{ token: { colorPrimary: "#00b96b" }, algorithm: algorithm.value }}>
        {slots.default?.()}
      </ConfigProvider>
    ));
  },
});
